package com.szpx.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service

public class MailService {

    @Value("${spring.mail.username}")
    private String mailUsername;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private TemplateEngine templateEngine;
    /*
    激活邮箱
     */
    public void sendMailForActivationAccount(String activationUrl,String email){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //创建邮件对象
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);
            //设置邮箱主题
            message.setSubject("欢迎来到丽江新中数影城");
            //设置发送者
            message.setFrom(mailUsername);
            //设置接收者
            message.setTo(email);
            //设置日期
            message.setSentDate(new Date());
            //设置上下文
            Context context = new Context();

            context.setVariable("activationUrl",activationUrl);
            String text = templateEngine.process("activation-account.html",context);

            //邮箱发送
            message.setText(text,true);
        } catch (MessagingException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
        }
        javaMailSender.send(mimeMessage);


        //设置
    }
}
